<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ECJTU 学生成绩分析系统</title>
    <script src="chart.js"></script>
    <script src="axios.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .navbar {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 1rem 0;
            margin-bottom: 20px;
            border-radius: 15px;
        }

        .navbar .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .navbar h1 {
            color: white;
            font-size: 1.5rem;
            font-weight: 600;
        }

        .nav-links {
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .nav-link {
            color: white;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 8px;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.1);
        }

        .nav-link:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-1px);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            padding: 25px;
            margin-bottom: 25px;
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 20px;
            color: #4a5568;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }

        .chart-container {
            position: relative;
            height: 400px;
            margin: 20px 0;
        }

        .analysis-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .analysis-card {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 20px;
            border-radius: 8px;
        }

        .analysis-title {
            font-weight: 600;
            color: #4a5568;
            margin-bottom: 10px;
        }

        .analysis-content {
            line-height: 1.6;
        }

        .strength-item, .improvement-item {
            background: white;
            padding: 10px;
            margin: 8px 0;
            border-radius: 5px;
            border-left: 3px solid #48bb78;
        }

        .improvement-item {
            border-left-color: #ed8936;
        }

        .course-breakdown {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .course-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            border-top: 3px solid #667eea;
        }

        .course-name {
            font-weight: 600;
            margin-bottom: 5px;
        }

        .course-trend {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            margin-bottom: 8px;
        }

        .trend-excellent {
            background: #c6f6d5;
            color: #22543d;
        }

        .trend-stable {
            background: #bee3f8;
            color: #2a4365;
        }

        .trend-fluctuating {
            background: #feebc8;
            color: #744210;
        }

        .error-message {
            background: #fed7d7;
            color: #c53030;
            padding: 15px;
            border-radius: 8px;
            margin: 10px 0;
        }

        .success-message {
            background: #c6f6d5;
            color: #22543d;
            padding: 15px;
            border-radius: 8px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="container">
            <h1>🎓 ECJTU AI</h1>
            <div class="nav-links">
                <a href="/" class="nav-link">🏠 首页</a>
                <a href="/dashboard" class="nav-link">📊 成绩分析</a>
                <a href="/schedule" class="nav-link">📅 课程表</a>
                <a href="/login" class="nav-link">🔐 登录</a>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <div class="header">
            <h1>🎓 ECJTU 学生成绩分析系统</h1>
            <p>智能分析您的学业表现，助力学术成长</p>
        </div>

        <div class="card">
            <div class="card-title">📊 数据获取与分析</div>
            <button class="btn" onclick="loadScores()">获取成绩数据</button>
            <button class="btn" onclick="analyzeScores()">AI 智能分析</button>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在处理中，请稍候...</p>
            </div>
        </div>

        <div id="stats-section" style="display: none;">
            <div class="card">
                <div class="card-title">📈 成绩概览</div>
                <div class="stats-grid" id="stats-grid">
                    <!-- 统计数据将在这里动态生成 -->
                </div>
            </div>
        </div>

        <div id="charts-section" style="display: none;">
            <div class="card">
                <div class="card-title">📊 成绩趋势图表</div>
                <div class="chart-container">
                    <canvas id="semesterChart"></canvas>
                </div>
            </div>

            <div class="card">
                <div class="card-title">🎯 学科分布</div>
                <div class="chart-container">
                    <canvas id="subjectChart"></canvas>
                </div>
            </div>
        </div>

        <div id="analysis-section" style="display: none;">
            <div class="card">
                <div class="card-title">🤖 AI 智能分析报告</div>
                <div id="analysis-content">
                    <!-- AI分析结果将在这里显示 -->
                </div>
            </div>
        </div>

        <div id="message-area"></div>
    </div>

    <script>
        let scoresData = null;
        let analysisData = null;

        function showLoading() {
            document.getElementById('loading').style.display = 'block';
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }

        function showMessage(message, type = 'success') {
            const messageArea = document.getElementById('message-area');
            const messageClass = type === 'error' ? 'error-message' : 'success-message';
            messageArea.innerHTML = `<div class="${messageClass}">${message}</div>`;
            setTimeout(() => {
                messageArea.innerHTML = '';
            }, 5000);
        }

        async function loadScores() {
            showLoading();
            try {
                const response = await fetch('/api/scores');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                scoresData = await response.json();
                
                if (scoresData.success) {
                    showMessage('成绩数据加载成功！');
                    displayStats();
                    displayCharts();
                } else {
                    showMessage(scoresData.message, 'error');
                }
            } catch (error) {
                showMessage('获取成绩数据失败：' + error.message, 'error');
            } finally {
                hideLoading();
            }
        }

        async function analyzeScores() {
            showLoading();
            try {
                const response = await fetch('/api/analyze');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                analysisData = await response.json();
                
                if (analysisData.success) {
                    showMessage('AI分析完成！');
                    displayAnalysis();
                } else {
                    showMessage(analysisData.message, 'error');
                }
            } catch (error) {
                showMessage('AI分析失败：' + error.message, 'error');
            } finally {
                hideLoading();
            }
        }

        function displayStats() {
            if (!scoresData) return;
            
            const statsGrid = document.getElementById('stats-grid');
            const data = scoresData.data;
            
            let totalCourses = 0;
            let totalCredits = 0;
            let gradeSum = 0;
            let gradeCount = 0;
            
            Object.values(data).forEach(semester => {
                totalCourses += semester.course_count;
                semester.courses.forEach(course => {
                    totalCredits += course.credit;
                    const grade = parseGrade(course.grade);
                    if (grade > 0) {
                        gradeSum += grade;
                        gradeCount++;
                    }
                });
            });
            
            const avgGrade = gradeCount > 0 ? (gradeSum / gradeCount).toFixed(1) : 0;
            
            statsGrid.innerHTML = `
                <div class="stat-card">
                    <div class="stat-number">${scoresData.total_semesters}</div>
                    <div class="stat-label">学期数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${totalCourses}</div>
                    <div class="stat-label">总课程数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${totalCredits}</div>
                    <div class="stat-label">总学分</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${avgGrade}</div>
                    <div class="stat-label">平均分</div>
                </div>
            `;
            
            document.getElementById('stats-section').style.display = 'block';
        }

        function parseGrade(grade) {
            if (typeof grade === 'number') return grade;
            if (grade === '优秀') return 95;
            if (grade === '良好') return 85;
            if (grade === '合格') return 75;
            if (grade === '不合格') return 50;
            return parseFloat(grade) || 0;
        }

        function displayCharts() {
            if (!scoresData) return;
            
            // 学期趋势图
            const semesterLabels = [];
            const semesterAvgs = [];
            
            Object.entries(scoresData.data).forEach(([semester, data]) => {
                semesterLabels.push(semester);
                let sum = 0;
                let count = 0;
                data.courses.forEach(course => {
                    const grade = parseGrade(course.grade);
                    if (grade > 0) {
                        sum += grade;
                        count++;
                    }
                });
                semesterAvgs.push(count > 0 ? (sum / count).toFixed(1) : 0);
            });
            
            const semesterCtx = document.getElementById('semesterChart').getContext('2d');
            new Chart(semesterCtx, {
                type: 'line',
                data: {
                    labels: semesterLabels,
                    datasets: [{
                        label: '学期平均分',
                        data: semesterAvgs,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: false,
                            min: 60,
                            max: 100
                        }
                    }
                }
            });
            
            // 学科分布图
            const subjects = {};
            Object.values(scoresData.data).forEach(semester => {
                semester.courses.forEach(course => {
                    const subject = getSubjectCategory(course.course_name);
                    if (!subjects[subject]) subjects[subject] = [];
                    subjects[subject].push(parseGrade(course.grade));
                });
            });
            
            const subjectLabels = Object.keys(subjects);
            const subjectAvgs = subjectLabels.map(subject => {
                const grades = subjects[subject].filter(g => g > 0);
                return grades.length > 0 ? (grades.reduce((a, b) => a + b) / grades.length).toFixed(1) : 0;
            });
            
            const subjectCtx = document.getElementById('subjectChart').getContext('2d');
            new Chart(subjectCtx, {
                type: 'radar',
                data: {
                    labels: subjectLabels,
                    datasets: [{
                        label: '各学科平均分',
                        data: subjectAvgs,
                        borderColor: '#764ba2',
                        backgroundColor: 'rgba(118, 75, 162, 0.2)',
                        pointBackgroundColor: '#764ba2'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        r: {
                            beginAtZero: false,
                            min: 60,
                            max: 100
                        }
                    }
                }
            });
            
            document.getElementById('charts-section').style.display = 'block';
        }

        function getSubjectCategory(courseName) {
            if (courseName.includes('数学') || courseName.includes('概率') || courseName.includes('线性代数')) return '数学类';
            if (courseName.includes('物理')) return '物理类';
            if (courseName.includes('英语')) return '英语类';
            if (courseName.includes('程序设计') || courseName.includes('Java') || courseName.includes('Python') || courseName.includes('数据结构')) return '编程类';
            if (courseName.includes('体育')) return '体育类';
            if (courseName.includes('政治') || courseName.includes('马克思') || courseName.includes('形势') || courseName.includes('思想')) return '政治类';
            if (courseName.includes('电路') || courseName.includes('电子') || courseName.includes('数字逻辑')) return '电子类';
            if (courseName.includes('计算机') || courseName.includes('网络') || courseName.includes('数据库')) return '计算机类';
            return '其他';
        }

        function displayAnalysis() {
            if (!analysisData || !analysisData.analysis) return;
            
            const analysis = analysisData.analysis;
            const content = document.getElementById('analysis-content');
            
            content.innerHTML = `
                <div class="analysis-section">
                    <div class="analysis-card">
                        <div class="analysis-title">📋 总体评估</div>
                        <div class="analysis-content">
                            <p><strong>GPA:</strong> ${analysis.overallAssessment.gpa}</p>
                            <p><strong>等级:</strong> ${analysis.overallAssessment.level}</p>
                            <p>${analysis.overallAssessment.summary}</p>
                        </div>
                    </div>
                    
                    <div class="analysis-card">
                        <div class="analysis-title">📈 学习趋势</div>
                        <div class="analysis-content">
                            <p><strong>趋势:</strong> ${analysis.learningTrajectory.trend}</p>
                            <p>${analysis.learningTrajectory.analysis}</p>
                        </div>
                    </div>
                </div>
                
                <div class="analysis-section">
                    <div class="analysis-card">
                        <div class="analysis-title">💪 优势领域</div>
                        <div class="analysis-content">
                            ${analysis.performanceAnalysis.strengths.map(strength => 
                                `<div class="strength-item">${strength}</div>`
                            ).join('')}
                        </div>
                    </div>
                    
                    <div class="analysis-card">
                        <div class="analysis-title">🎯 待提升领域</div>
                        <div class="analysis-content">
                            ${analysis.performanceAnalysis.areasForImprovement.map(area => 
                                `<div class="improvement-item">${area}</div>`
                            ).join('')}
                        </div>
                    </div>
                </div>
                
                <div class="analysis-card">
                    <div class="analysis-title">💡 个性化建议</div>
                    <div class="analysis-content">
                        <h4>学术建议：</h4>
                        ${analysis.personalizedSuggestions.academic.map(suggestion => 
                            `<div class="strength-item">${suggestion}</div>`
                        ).join('')}
                        
                        <h4>发展建议：</h4>
                        ${analysis.personalizedSuggestions.developmental.map(suggestion => 
                            `<div class="strength-item">${suggestion}</div>`
                        ).join('')}
                    </div>
                </div>
                
                <div class="analysis-card">
                    <div class="analysis-title">📚 关键课程分析</div>
                    <div class="course-breakdown">
                        ${analysis.keyCourseBreakdown.map(course => `
                            <div class="course-card">
                                <div class="course-name">${course.courseName}</div>
                                <div class="course-trend trend-${course.trend === '优秀' ? 'excellent' : course.trend === '稳定' ? 'stable' : 'fluctuating'}">
                                    ${course.trend}
                                </div>
                                <div>${course.comment}</div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
            
            document.getElementById('analysis-section').style.display = 'block';
        }
    </script>
</body>
</html>